package br.ucb.cm.main.mainview;

import javax.swing.JOptionPane;
import br.ucb.cm.config.GameInstance;
import br.ucb.cm.config.bean.Config;
import br.ucb.cm.config.dao.ConfigDAO;
import br.ucb.cm.config.dao.ConfigDAOFactory;
import br.ucb.cm.config.dao.DAOException;
import br.ucb.cm.config.wizard.ConfigWizard;
import br.ucb.cm.main.mainview.ui.IfcMainView;
import br.ucb.cm.main.mainview.ui.MainViewUI;

public class MainView implements IfcMainView{
	private MainViewUI ui;
	private ConfigWizard configuration;
	private ConfigDAO configDAO;

	public MainView() {
		this.configuration = new ConfigWizard();
		initUi();

		this.configDAO = ConfigDAOFactory.createNewConfigDAO();
	}

	private void initUi() {

		this.ui = new MainViewUI(this);
		this.ui.setTitle("Custom Moves");
		this.ui.setVisible(true);
	}

	@Override
	public void doAction(ActionEnum action) {
		switch (action) {
		case NEW_CONF:
			getConfiguration().show();
			break;
		case NEW_GAME:
			NewGame newGame = new NewGame();
			newGame.show();

			if(!newGame.isConfigLoaded())
				return;

			startGame();
			break;
		case CONFIG_UNLOADED:
			unloadConfig();
			System.gc();
			break;
		case QUIT:
			System.exit(0);
			break;
		default:
			break;
		}
	}

	private void startGame() {
		GameController controller = new GameController();
		getUi().showGamePane(controller.getGamePane());

		controller.startGame();
	}

	public MainViewUI getUi() {
		return ui;
	}

	public void setUi(MainViewUI ui) {
		this.ui = ui;
	}

	public ConfigDAO getConfigDAO() {
		return configDAO;
	}

	public void setConfigDAO(ConfigDAO configDAO) {
		this.configDAO = configDAO;
	}

	@Override
	public void doAction(ActionEnum action, String absolutePath) {
		if(action == ActionEnum.OPEN_CONF){
			loadConfig(absolutePath);
		}
	}

	private void loadConfig(String absolutePath) {
		Config config = null;

		try {	
			config = getConfigDAO().getFrom(absolutePath);
		} catch (DAOException e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE, null);
			e.printStackTrace();
		}

		if(config != null){
			GameInstance.getInstance().loadConfig(config);
			getUi().changeUIConfig(ActionEnum.CONFIG_LOADED);
		}		
	}

	public ConfigWizard getConfiguration() {
		return configuration;
	}

	public void setConfiguration(ConfigWizard configuration) {
		this.configuration = configuration;
	}

	private void unloadConfig() {
		GameInstance.getInstance().unloadConfig();
		getUi().changeUIConfig(ActionEnum.CONFIG_UNLOADED);
	}
}
